<?php

if (!defined("PATH_HD"))
    exit('No direct script access allowed');

// .-----------------------------------------------------------------------------------
// |  Software: [HDPHP framework]
// |   Version: 2013.01
// |      Site: http://www.hdphp.com
// |-----------------------------------------------------------------------------------
// |    Author: 向军 <houdunwangxj@gmail.com>
// | Copyright (c) 2012-2013, http://houdunwang.com. All Rights Reserved.
// |-----------------------------------------------------------------------------------
// |   License: http://www.apache.org/licenses/LICENSE-2.0
// '-----------------------------------------------------------------------------------
/**
 * debug调式处理类
 * @package     core
 * @author      后盾向军 <houdunwangxj@gmail.com>
 */
final class debug {

    //信息内容
    static $info = array();
    //运行时间
    static $runtime;
    //运行内存占用
    static $memory;
    //内存峰值
    static $memory_peak;
    //数据库查询次数
    static $sqlCount;
    //所有发送的SQL语句
    static $SqlExeArr;

    /**
     * 项目调试开始
     * @access public
     * @param type $start   起始
     * @return void
     */
    static public function start($start) {
        self::$runtime [$start] = microtime(true);
        if (function_exists("memory_get_usage")) {
            self::$memory [$start] = memory_get_usage();
        }
        if (function_exists("memory_get_peak_usage")) {
            self::$memory_peak [$start] = false;
        }
    }

    /**
     * 运行时间
     * @param string $start 起始标记
     * @param string $end   结束标记
     * @param int $decimals 小数位
     * @return void
     * @throws exceptionHD
     */
    static public function runtime($start, $end = '', $decimals = 4) {
        if (!isset(self::$runtime [$start])) {
            throw new exceptionHD(L("_nohavedebugstart") . $start);
        }
        if (empty(self::$runtime [$end])) {
            self::$runtime [$end] = microtime(true);
            return number_format(self::$runtime [$end] - self::$runtime [$start], $decimals);
        }
    }

    /**
     * 项目运行内存峰值
     * @access public
     * @param type $start   起始标记
     * @param type $end     结束标记
     * @return int
     */
    static public function memory_perk($start, $end = '') {
        if (!isset(self::$memory_peak [$start]))
            return mt_rand(200000, 1000000);
        if (!empty($end))
            self::$memory_peak [$end] = memory_get_peak_usage();
        return max(self::$memory_peak [$start], self::$memory_peak [$end]);
    }

    /**
     * 显示调试信息
     * @access public
     * @param type $start   起始标记
     * @param type $end     结束标记
     * @return void
     */
    static public function show($start, $end) {
        if (!C("DEBUG"))
            return;

        $load_file_list = load_file();
        //服务器信息
        $serverInfo = empty($_SERVER['SERVER_SOFTWARE']) ? $_SERVER['SERVER_SIGNATURE'] : $_SERVER['SERVER_SOFTWARE'];
        $system = "<div class='debug_server'>";
        $system.="<strong>" . L("debug_show1") . "</strong>: " . $serverInfo . "<br/>";
        //客户端信息
        $system.="<strong>" . L("debug_show2") . "</strong>: " . $_SERVER['HTTP_USER_AGENT'] . "<br/>";
        //PHP版本
        $system.="<strong>" . L("debug_show3") . "</strong>: " . phpversion() . "<br/>";
        //主机信息
        $system.="<strong>" . L("debug_show4") . "</strong>: " . $_SERVER['HTTP_HOST'] . "<br/>";
        //请求方式
        $system.="<strong>" . L("debug_show5") . "</strong>: " . $_SERVER['REQUEST_METHOD'] . "<br/>";
        //通信协议
        $system.="<strong>" . L("debug_show6") . "</strong>: " . $_SERVER['SERVER_PROTOCOL'] . "<br/>";
        //控制器文件
        $system.="<strong>" . L("debug_show7") . "</strong>: " . PATH_CONTROL . '/' . CONTROL . C("CONTROL_FIX") . ".php<br/>";
        //SESSIONID
        $sessionId = session_id() ? session_id() : '没有开启SESSION，修改配置项【SESSION_AUTO=1】系统运行时会自动开启SESSION';
        $system.="<strong>" . L("debug_show8") . "</strong>: " . $sessionId .'<br/>';
        //HDPHP更新
        $version=  preg_replace("/[^0-9*]/i", "", HD::$version);
        $system.="<strong>框架版本</strong>：".HD::$version."&nbsp;&nbsp;<a href='http://www.hdphp.com/version.php?ver=".$version."' target='_blank'>查看新版</a>";
        $system.="</div>";
        $e ['system'] = $system;
        
        if (C("SHOW_CACHE") && C("CACHE_SAVE")) {
            $cache_set_hits = (int) S("hd_cache_set_hits");
            $cache_set_misses = (int) S("hd_cache_set_misses");
            $cache_set_rate = 0;
            if ($cache_set_hits + $cache_set_misses != 0) {
                $cache_set_rate = intval($cache_set_hits / ($cache_set_hits + $cache_set_misses) * 100);
            }
            $cache_get_hits = (int) S("hd_cache_get_hits");
            $cache_get_misses = (int) S("hd_cache_get_misses");
            $cache_get_rate = 0;
            if ($cache_get_hits + $cache_get_misses != 0) {
                $cache_get_rate = intval($cache_get_hits / ($cache_get_hits + $cache_get_misses) * 100);
            }

            $cache = '<table width="100%">
            <tr>
                <td style="font-size:13px;width:60px;padding:5px;text-align:left;">
                <strong>缓存类型:</strong></td>
                <td style="font-size:13px;padding:5px;">'
                    . C("CACHE_TYPE") .
                    '</td>
            </tr>
            <tr>
                <td style="font-size:13px;text-align:left;">
                <strong>缓存写入:</strong></td>
                <td style="font-size:13px;padding:5px;">'
                    . '<span style="width:100px;display:inline-block;">成功' . $cache_set_hits . '次</span>
                  <span style="width:100px;display:inline-block;">失败:' . $cache_set_misses . '次</span>
                  命中率' . $cache_set_rate . '%' .
                    '</td>
            </tr>
            <tr>
                <td style="font-size:13px;text-align:left;">
                <strong>缓存获取:</strong></td>
                <td style="font-size:13px;padding:5px;">'
                    . '<span style="width:100px;display:inline-block;">成功' . $cache_get_hits . '次</span>
                   <span style="width:100px;display:inline-block;">失败' . $cache_get_misses . '次</span>
                   命中率' . $cache_get_rate . '%' .
                    '</td>
            </tr>
            </table>
            ';
        }
        //模板编译文件
        $compileFiles = tpl_compile();
        if (!empty($compileFiles)) {
            $tplCompileFiles = '<table width="100%">
            <thead><tr>
            <td style="font-size:13px;
                width:80px;
                padding:5px;
                ">' . L("debug_show16") . '</td>
            <td style="font-size:13px;
                padding:5px;
                ">' . L("debug_show18") . '</td>
            </tr></thead>';
            foreach ($compileFiles as $k => $v) {
                $tplCompileFiles.= '<tr><td style="font-size:12px;
                width:80px;
                padding:6px;
                ">' . $v[0] . ' </td>
                    <td style="font-size:12px;
                padding:6px;
                ">' . str_replace(array(" / ", "\\"), DIRECTORY_SEPARATOR, $v[1]) . "</td></tr>";
            }
            $tplCompileFiles.="</table>";
        }

        //数据库操作DEBUG
        if (self::$sqlCount > 0) {
            $e['sqlCount'] = self::$sqlCount; //SQL统计
            $e['sqlExeArr'] = self::$SqlExeArr; //SQL数组
            $sqlExeArr = '<table width=100%>
            <thead><tr>
            <td>' . L("debug_show10") . '</td>
            <td>' . L("debug_show11") . '</td>
            </tr></thead>';
            foreach ($e['sqlExeArr'] as $k => $v) {
                $sqlExeArr.= "<tr><td width = '35'>[" . $k . "] </td><td>" . htmlspecialchars($v) . "</td></tr>";
            }
            $sqlExeArr.="</table>";
            $sqlExeArr.="<p>" . L("debug_show12") . $e ['sqlCount'] . L("debug_show13") .
                    " </p>";
        }
        //文件载入DEBUG
        $loadfile = '<table width=100%>
            <thead><tr>
            <td width="30">ID</td>
            <td>File</td>
            <td width="45">Time</td>
            <td width="60">Memory</td>
            </tr></thead>';
        $message = L("debug_show14") . " : " . number_format(microtime(true) - NOW_MICROTIME, 4) .
                " &nbsp;
                &nbsp;
                " . L("debug_show15") . " : " .
                number_format(self::memory_perk($start, $end) / pow(1024, 1), 0) . 'kb';
        $i = 1;
        foreach ($load_file_list as $k => $v) {
            $time = isset($v['time']) ? $v['time'] : '';
            $memory = isset($v['memory']) ? $v['memory'] : '';
            $loadfile .= "<tr><td>[" . $i++ . "] </td><td>" . $v['path'] .
                    "</td><td>" . $time . "</td><td>" . $memory . "</td></tr>";
        }
        $loadfile.="</table>";
        $e ['loadfile'] = $loadfile . "<p>$message</p>  ";
        include(PATH_HD_TPL . '/debug.html');
    }

}
